/**
 * 邮件发送历史页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Tooltip,
  DatePicker,
} from 'antd';
import {
  SendOutlined,
  ReloadOutlined,
  SearchOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import {
  getEmailSendHistory,
  type EmailSendHistory,
  EmailSendStatus,
} from '@/services/emailSend';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;

const EmailHistoryPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<EmailSendHistory[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<EmailSendStatus | undefined>();
  const [taskIdFilter, setTaskIdFilter] = useState('');
  const [dateRange, setDateRange] = useState<[moment.Moment, moment.Moment] | null>(null);

  // 获取邮件发送历史
  const fetchEmailHistory = async () => {
    setLoading(true);
    try {
      const response = await getEmailSendHistory({
        page: current,
        size: pageSize,
        search: searchText || undefined,
        status: statusFilter,
        task_id: taskIdFilter || undefined,
      });
      setData(response.items);
      setTotal(response.total);
    } catch (error: any) {
      console.error('获取邮件发送历史失败:', error);
      // message.error(error.message || '获取邮件发送历史失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmailHistory();
  }, [current, pageSize, searchText, statusFilter, taskIdFilter]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrent(1);
  };

  // 处理任务ID过滤
  const handleTaskIdFilter = (value: string) => {
    setTaskIdFilter(value);
    setCurrent(1);
  };

  // 获取状态标签
  const getStatusTag = (status: EmailSendStatus) => {
    const statusMap = {
      [EmailSendStatus.PENDING]: { color: 'default', text: '等待发送' },
      [EmailSendStatus.SENT]: { color: 'success', text: '发送成功' },
      [EmailSendStatus.FAILED]: { color: 'error', text: '发送失败' },
      [EmailSendStatus.BOUNCED]: { color: 'warning', text: '邮件退回' },
    };
    const config = statusMap[status] || statusMap[EmailSendStatus.PENDING];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列定义
  const columns: ColumnsType<EmailSendHistory> = [
    {
      title: '任务ID',
      dataIndex: 'task_id',
      key: 'task_id',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text.substring(0, 8)}...</span>
        </Tooltip>
      ),
    },
    {
      title: '收件人邮箱',
      dataIndex: 'recipient_email',
      key: 'recipient_email',
      ellipsis: true,
    },
    {
      title: '收件人姓名',
      dataIndex: 'recipient_name',
      key: 'recipient_name',
      width: 120,
      render: (text: string) => text || '-',
    },
    {
      title: '邮件主题',
      dataIndex: 'subject',
      key: 'subject',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '发送状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: EmailSendStatus) => getStatusTag(status),
    },
    {
      title: '发送时间',
      dataIndex: 'sent_at',
      key: 'sent_at',
      width: 150,
      render: (text: string) => text ? new Date(text).toLocaleString() : '-',
    },
    {
      title: '消息ID',
      dataIndex: 'message_id',
      key: 'message_id',
      width: 120,
      render: (text: string) => text ? (
        <Tooltip title={text}>
          <span>{text.substring(0, 8)}...</span>
        </Tooltip>
      ) : '-',
    },
    {
      title: '错误信息',
      dataIndex: 'error_message',
      key: 'error_message',
      width: 200,
      ellipsis: true,
      render: (text: string) => text ? (
        <Tooltip title={text}>
          <span style={{ color: '#ff4d4f' }}>{text}</span>
        </Tooltip>
      ) : '-',
    },
  ];

  return (
    <PageContainer
      header={{
        title: '邮件发送历史',
        breadcrumb: {},
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Search
              placeholder="搜索收件人邮箱或主题"
              allowClear
              style={{ width: 250 }}
              onSearch={handleSearch}
            />
            <Input
              placeholder="任务ID"
              allowClear
              style={{ width: 150 }}
              onChange={(e) => handleTaskIdFilter(e.target.value)}
            />
            <Select
              placeholder="发送状态"
              allowClear
              style={{ width: 120 }}
              value={statusFilter}
              onChange={setStatusFilter}
            >
              <Option value={EmailSendStatus.PENDING}>等待发送</Option>
              <Option value={EmailSendStatus.SENT}>发送成功</Option>
              <Option value={EmailSendStatus.FAILED}>发送失败</Option>
              <Option value={EmailSendStatus.BOUNCED}>邮件退回</Option>
            </Select>
            <RangePicker
              style={{ width: 250 }}
              value={dateRange}
              onChange={setDateRange}
              placeholder={['开始日期', '结束日期']}
            />
            <Button icon={<ReloadOutlined />} onClick={fetchEmailHistory}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={() => history.push('/emails/send')}
            >
              发送邮件
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size || 10);
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>
    </PageContainer>
  );
};

export default EmailHistoryPage;
